package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.IdCardUtil;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-04
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;



    /**
     * 查询入住信息
     * 
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住信息列表
     * 
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住信息
     * 
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住信息
     * 
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息信息
     * 
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     * @param dto 入住申请信息
     * @return  1成功，0失败
     */
    @Override
    @Transactional
    public int applyCheckIn(CheckInApplyDto dto) {
        //1.校验老人是否已经入住
        LambdaQueryWrapper<Elder> qw = new LambdaQueryWrapper<>();
        qw.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        Elder elderDB = this.elderMapper.selectOne(qw);
        //1.1、是，则抛出业务异常，结束方法，否则继续向下运行
        if (elderDB != null && elderDB.getStatus() != 5){
            throw new ServiceException("该老人已入住，请勿重复入住!");
        }

        //1.2、更新床位状态为已入住
        //TODO床位是否已经住入
//        LambdaQueryWrapper<Bed> bedqw = new LambdaQueryWrapper<>();
//        bedqw.eq(Bed::getId,dto.getCheckInConfigDto().getBedId());
//        Bed bedDB2 = this.bedMapper.selectOne(bedqw);
//        if (bedDB2.getBedStatus() != 0){
//            throw new ServiceException("该床位已入住，请勿重复入住!");
//        }
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = this.bedMapper.selectById(bedId);
        if (bed==null || bed.getBedStatus() != 0){
            throw new ServiceException("该床位已入住，请勿重复入住!");
        }

//        Long bedId = dto.getCheckInConfigDto().getBedId();
       // Bed bed = new Bed();
        //bed.setId(bedId);
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //2新增或者更新老人数据
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder = new Elder();
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        BeanUtils.copyProperties(checkInElderDto,elder);
//        elder.setPhone(checkInElderDto.getPhone());
        if (elderDB != null){
            //更新老人数据
            elder.setId(elderDB.getId());
            this.elderMapper.updateById(elder);
        }else {
            //新增老人数据
            this.elderMapper.insert(elder);
        }
        //3新增签约办理
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        //3.1、补全数据
        contract.setElderId(elder.getId());
        //3.1.2、生成合同编号
        String contractNo ="HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        //3.1.3、生成老人姓名
        contract.setElderName(elder.getName());
        //3.1.4、设置时间和状态
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        int status = startDate.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        this.contractMapper.insert(contract);

        //4新增入住信息
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
//        Bed bedDB = this.bedMapper.selectBedById(bedId);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        //老人家属信息
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        this.checkInMapper.insert(checkIn);
        //5新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        this.checkInConfigMapper.insert(checkInConfig);
        return 1;
    }

    /**
     * 获取入住详情
     * @param id 入住ID
     * @return 入住详情
     */
    @Override
    public CheckInDetailVo selectCheckInDetail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.查询入住信息
        CheckIn checkIn = this.checkInMapper.selectById(id);
        //2.查询老人信息
        Elder elder = this.elderMapper.selectById(checkIn.getElderId());
        //2.1、数据拷贝 Elder -> CheckInElderVo
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyBeanProp(checkInElderVo,elder);
        //2.2、TODO 获取年龄，数据库没这个字段，用身份证号算
        int age = IdCardUtil.getAgeByIdCard(elder.getIdCardNo());
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //3.查询合同信息
        LambdaQueryWrapper<Contract> ctqw = new LambdaQueryWrapper<>();
        ctqw.eq(Contract::getElderId,elder.getId());
        Contract contract = this.contractMapper.selectOne(ctqw);
        checkInDetailVo.setContract(contract);
        //4.查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> ciqw = new LambdaQueryWrapper<>();
        ciqw.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = this.checkInConfigMapper.selectOne(ciqw);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyBeanProp(checkInConfigVo,checkInConfig);
        //4.1、缺入住时间配置信息
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //5.查询老人家属信息
        String remark = checkIn.getRemark();
        //5.1、JSON字符串转换成对象
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        return checkInDetailVo;
    }
}
